// Popup script to handle the extension UI

// DOM elements
const videoList = document.getElementById('videoList');
const emptyState = document.getElementById('emptyState');
const videoCount = document.getElementById('videoCount');
const refreshBtn = document.getElementById('refreshBtn');
const clearBtn = document.getElementById('clearBtn');

// Load videos when popup is opened
document.addEventListener('DOMContentLoaded', () => {
  loadVideos();
});

// Refresh button event listener
refreshBtn.addEventListener('click', () => {
  refreshVideos();
});

// Clear button event listener
clearBtn.addEventListener('click', () => {
  clearVideos();
});

// Function to load videos from background script
function loadVideos() {
  chrome.runtime.sendMessage({ action: 'getDetectedVideos' }, (response) => {
    if (chrome.runtime.lastError) {
      console.error('Error getting videos:', chrome.runtime.lastError);
      // Show error in UI
      videoList.innerHTML = `<div class="empty-state">
        <div>❌</div>
        <p>获取视频列表时出错</p>
        <p>${chrome.runtime.lastError.message}</p>
      </div>`;
      return;
    }
    
    if (!response) {
      console.error('Empty response from background script');
      videoList.innerHTML = `<div class="empty-state">
        <div>❌</div>
        <p>从背景脚本接收到空响应</p>
        <p>请尝试刷新页面</p>
      </div>`;
      return;
    }
    
    if (!Array.isArray(response.videos)) {
      console.error('Invalid response format from background script:', response);
      videoList.innerHTML = `<div class="empty-state">
        <div>❌</div>
        <p>从背景脚本接收到无效数据格式</p>
        <p>请尝试刷新页面</p>
      </div>`;
      return;
    }
    
    console.log('Videos received from background script:', response.videos);
    displayVideos(response.videos);
  });
}

// Function to display videos in the popup
function displayVideos(videos) {
  // Update video count
  videoCount.textContent = videos.length;
  
  // Show or hide empty state
  if (videos.length === 0) {
    emptyState.style.display = 'block';
    videoList.innerHTML = '';
    videoList.appendChild(emptyState);
    return;
  }
  
  // Hide empty state
  emptyState.style.display = 'none';
  
  // Clear current list
  videoList.innerHTML = '';
  
  // Add videos to the list
  videos.forEach(video => {
    const videoElement = createVideoElement(video);
    videoList.appendChild(videoElement);
  });
}

// Function to create a video element
function createVideoElement(video) {
  const div = document.createElement('div');
  div.className = 'video-item';
  
  // Format the page URL to show only the domain
  let domain = 'Unknown';
  try {
    const url = new URL(video.pageUrl);
    domain = url.hostname;
  } catch (e) {
    // Use the pageUrl as domain if URL parsing fails
    domain = video.pageUrl;
  }
  
  div.innerHTML = `
    <div class="video-title">${escapeHtml(video.title)}</div>
    <div class="video-url">${escapeHtml(video.url)}</div>
    <div class="video-page">${escapeHtml(domain)}</div>
    <div class="video-actions">
      <button class="download-btn" data-video-id="${video.id}" data-video-title="${escapeHtml(video.title)}">下载</button>
    </div>
  `;
  
  // Add event listener to download button
  const downloadBtn = div.querySelector('.download-btn');
  downloadBtn.addEventListener('click', () => {
    downloadVideo(video.id, video.title);
  });
  
  return div;
}

// Function to escape HTML to prevent XSS
function escapeHtml(text) {
  const map = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": '''
  };
  
  return text.replace(/[&<>"']/g, m => map[m]);
}

// Function to refresh videos
function refreshVideos() {
  // Show loading state
  refreshBtn.disabled = true;
  refreshBtn.textContent = '刷新中...';
  
  // Request current tab to run content script
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs[0]) {
      console.log('Refreshing videos for tab:', tabs[0].id);
      // Send message to content script to get videos
      chrome.tabs.sendMessage(tabs[0].id, { action: 'getHlsVideos' }, (response) => {
        if (chrome.runtime.lastError) {
          console.error('Error getting videos from content script:', chrome.runtime.lastError);
        } else if (response && response.videos) {
          console.log('Videos detected by content script:', response.videos);
          // Send videos to background script
          chrome.runtime.sendMessage({
            action: 'hlsVideosDetected',
            videos: response.videos,
            tabId: tabs[0].id
          }, (bgResponse) => {
            if (chrome.runtime.lastError) {
              console.error('Error sending videos to background script:', chrome.runtime.lastError);
            } else {
              console.log('Videos sent to background script successfully');
            }
          });
        } else {
          console.log('No videos detected by content script');
        }
        
        // Reload videos from background script
        setTimeout(() => {
          loadVideos();
          refreshBtn.disabled = false;
          refreshBtn.textContent = '刷新';
        }, 500);
      });
    } else {
      console.log('No active tab found');
      // Reload videos from background script
      loadVideos();
      refreshBtn.disabled = false;
      refreshBtn.textContent = '刷新';
    }
  });
}

// Function to download a video
function downloadVideo(videoId, videoTitle) {
  chrome.runtime.sendMessage({
    action: 'downloadVideo',
    videoId: videoId,
    videoTitle: videoTitle
  }, (response) => {
    if (chrome.runtime.lastError) {
      console.error('Error downloading video:', chrome.runtime.lastError);
    } else if (response && response.success) {
      // Show download confirmation
      const btn = document.querySelector(`[data-video-id="${videoId}"]`);
      if (btn) {
        const originalText = btn.textContent;
        btn.textContent = '下载中...';
        btn.disabled = true;
        
        // Reset button after a delay
        setTimeout(() => {
          btn.textContent = originalText;
          btn.disabled = false;
        }, 2000);
      }
    }
  });
}

// Function to clear videos
function clearVideos() {
  chrome.runtime.sendMessage({
    action: 'clearVideos'
  }, (response) => {
    if (response.success) {
      displayVideos([]);
    }
  });
}